/*
 * @Author: 飞越疯人院 353362604@qq.com
 * @Date: 2022-09-22 14:42:54
 * @LastEditors: 飞越疯人院 353362604@qq.com
 * @LastEditTime: 2022-12-29 16:56:52
 * @FilePath: \adminstration\src\Common\Configure\QRcode.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import { Modal, Button, message } from 'antd'
import { useState, useEffect, useRef } from 'react'
import { useEventEmitter, useBoolean } from 'ahooks'
import { API_LIST } from '../Api/Api'
import { saveAs } from 'file-saver'
import { initPrinter } from './Printer'
import Loading from '../Currency/Loading'
import QRCode from 'qrcode.react'

export const PrinterData = url => ({
    SampleParameter: [
        1,
        {
            width: 100,
            height: 70,
            rotate: 90,
            path: 'ZT001.ttf',
            verticalShift: 0,
            HorizontalShift: 0,
        },
        {
            x: 5,
            y: 5,
            width: 90,
            height: 63,
            rotate: 0,
            imageProcessingType: 0,
            imageProcessingValue: 127,
            imageData: url?.replace('data:image/png;base64,', ''),
        },
        3,
        1,
        1,
        1,
    ],
})

export const PictureStream = (getApi, getData, UrlEvent) => {
    axios
        .get(`${getApi}?${getData}`, { responseType: 'arraybuffer' })
        .then(
            response =>
                'data:image/png;base64,' +
                btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), '')),
        )
        .then(res => UrlEvent.emit(res))
}

export const ExportExcel = (getApi, getData = {}) => {
    if (getData) {
        if (getData.pageIndex) delete getData.pageIndex
        if (getData.pageSize) delete getData.pageSize
    }
    axios
        .get(getApi, { params: { ...getData, IsExport: 1 }, responseType: 'blob' })
        .then(res => {
            let textName = ''
            const nameArr = res.headers['content-disposition'].split(';')
            nameArr.forEach(item => {
                if (item.indexOf("filename*=UTF-8''") !== -1) textName = decodeURI(item.split("filename*=UTF-8''")[1])
            })
            saveAs(res.data, textName)
        })
        .catch(() => {
            message.error('系统错误')
        })
}

export const QRcode = ({ Off, data }) => {
    const [PrintState, { setTrue: PrintTrue, setFalse: PrintFalse }] = useBoolean(false)
    const { className, record, key } = data
    const UrlEvent = useEventEmitter()
    const [Url, setUrl] = useState()
    useEffect(
        () => setUrl(PictureStream(API_LIST()['getLabSampleQRImage'], `SampleItemUuid=${record.uuid}`, UrlEvent)),
        [record, UrlEvent],
    )
    UrlEvent.useSubscription(val => setUrl(val))
    const MarkEvent = useEventEmitter()
    MarkEvent.useSubscription(() => PrintFalse())
    return (
        <Modal
            className={`appendix ${className}`}
            open={true}
            footer={null}
            maskClosable={false}
            onCancel={Off}
            destroyOnClose
            title="查看二维码"
            centered
            width={600}
        >
            <div className="codeBox">
                <img src={Url} alt="" />
                <div>
                    <Button type="primary" size="large" onClick={() => saveAs(Url, '二维码.png')}>
                        下载二维码
                    </Button>
                    {key && (
                        <Button
                            type="primary"
                            size="large"
                            onClick={() => {
                                PrintTrue()
                                const [type, size, content, printDensity, printLabelType, printMode, count] =
                                    PrinterData(Url)[key]
                                initPrinter(
                                    type,
                                    size,
                                    content,
                                    printDensity,
                                    printLabelType,
                                    printMode,
                                    count,
                                    MarkEvent,
                                )
                            }}
                        >
                            打印二维码
                        </Button>
                    )}
                </div>
            </div>
            {PrintState && (
                <div className="MarkBox">
                    <Loading
                        text="打印中..."
                        color={{ background: 'radial-gradient(rgba(0,0,0,0.7), rgba(255,255,255,1))' }}
                    />
                </div>
            )}
        </Modal>
    )
}

export const CanvasQRcodeModal = ({ Off, data }) => {
    const Canvas = useRef(null)
    const { className, record } = data
    useEffect(() => {
        const { bridgeName, part, beamNo } = record
        const ctx = Canvas.current.getContext('2d')
        ctx.fillStyle = '#262626'
        ctx.fontWeight = 'bold'
        ctx.font = "30px '微软雅黑'"
        ctx.textAlign = 'center'
        ctx.fillText(`${bridgeName} ${part} ${beamNo}`, 250, 540)
        const canvasImg = document.getElementById('qrCode')
        const img = new Image()
        img.src = canvasImg.toDataURL('image/png')
        img.onload = () => ctx.drawImage(img, 0, 0)
    }, [record])

    const downLoadCod = () => {
        const canvasImg = document.getElementById('drawing')
        const img = new Image()
        img.src = canvasImg.toDataURL('image/png')
        const downLink = document.getElementById('down_link')
        downLink.href = img.src
        downLink.download = `${record.beamNo} 二维码`
    }

    return (
        <Modal
            className={`appendix ${className}`}
            open={true}
            footer={null}
            maskClosable={false}
            onCancel={Off}
            destroyOnClose
            title="查看二维码"
            centered
            width={600}
        >
            <div className="QRCode">
                <canvas ref={Canvas} id="drawing" width="500" height="560"></canvas>
                <QRCode
                    id="qrCode"
                    value={`http://tieke.ljkjkf.com/Qrcode/${record.beamUuid}`}
                    size={500}
                    fgColor="#000000"
                    style={{ margin: 'auto' }}
                />
                <a id="down_link" href="a" onClick={downLoadCod}>
                    下载二维码
                </a>
            </div>
        </Modal>
    )
}
